package com.hw.core.config;

import com.hw.core.system.controller.PublicController;
import com.hw.core.system.entity.Permission;
import com.hw.core.system.entity.Role;
import com.hw.core.system.entity.User;
import com.hw.core.system.repository.UserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Transactional(readOnly = true)//全部方法只读事务
public class ShiroRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger( ShiroRealm.class );
    @Autowired
    private UserRepository userRepository;

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        User user = userRepository.findUsersByName( username );
        logger.info( "对"+ username+"进行数据库用户密码验证");
        if (user == null) {
            throw new UnknownAccountException( "用户名密码错误!" );
        }

        if (user.getLocked()==0) {
            throw new LockedAccountException( "用户被锁定" );
        }
        user.setRole( null );

        Object credentials = user.getPassword();

        //加盐,默认使用用户名
        ByteSource salt = ByteSource.Util.bytes( username );
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo( user, credentials, salt, realmName );
        return info;
    }

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User u = (User) principalCollection.getPrimaryPrincipal();
        User user = userRepository.findUsersByName( u.getName() );
        logger.info( "对"+ u.getName()+"进行数据库权限验证");
        List<String> permissions = new ArrayList<>();
        Role role = user.getRole();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (role!=null) {
            List<Permission> permissions1 = role.getPermissions();
            for (Permission permission : permissions1) {
                permissions.add( permission.getName() );
            }
            info.addStringPermissions( permissions );
            info.addRole( role.getName() );
        }

        return info;
    }



}
